package com.util.gzp.mima;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * ClassName: AesUtils
 * Package: com.util.gzp.mima
 *
 * @author: guanzepeng
 * @Date: 2021/4/6 13:28 星期二
 * @Description: 密码加密解密
 */
@Slf4j
public class AesUtils {

	/**
	 * 加密因子
	 */
	private static String ENCODE_FACTOR = "76YQPE5YGJN7F3UQ";

	private static String KEY_ALGORITHM = "AES";

	private static String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

	/**
	 * 测试
	 *
	 * @param args
	 * @author libin
	 */
	public static void main(String[] args)
	{
		String text = "vzIgqZyg/HLFSm/2v163vg==";
//		String encode = encode(text);
//		System.out.println(encode);
		String decode = decode(text);
		System.out.println(decode);
	}

	/**
	 * 加密
	 *
	 * @param txt 需要加密的字符串
	 * @return
	 * @author libin
	 */
	public static String encode(String txt)
	{
		return encode(txt, ENCODE_FACTOR);
	}

	/**
	 * 加密
	 *
	 * @param txt    需要加密的字符串
	 * @param factor 加密因子
	 * @author libin
	 */
	public static String encode(String txt, String factor)
	{
		try
		{
			// "算法/模式/补码方式"
			Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
			SecretKey key = new SecretKeySpec(factor.getBytes("utf-8"), KEY_ALGORITHM);

			// 初始化密码器，第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作，第二个参数为使用的KEY
			cipher.init(Cipher.ENCRYPT_MODE, key);

			byte[] encrypted = cipher.doFinal(txt.getBytes("utf-8"));

			// 将字符串返回
			return Base64.encodeBase64String(encrypted);
		}
		catch (Exception e)
		{
			log.error("加密失败", e);
			throw new RuntimeException("加密失败", e);
		}
	}

	/**
	 * 解密
	 *
	 * @param txt
	 * @return
	 * @author libin
	 */
	public static String decode(String txt)
	{
		return decode(txt, ENCODE_FACTOR);
	}

	/**
	 * 解密
	 *
	 * @param txt    需要解密的字符串
	 * @param factor 解密因子
	 * @return String
	 */
	public static String decode(String txt, String factor)
	{

		try
		{
			// "算法/模式/补码方式"
			Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
			SecretKey key = new SecretKeySpec(factor.getBytes("utf-8"), KEY_ALGORITHM);

			// 初始化密码器，第一个参数为加密(DECRYPT_MODE)或者解密解密(DECRYPT_MODE)操作，第二个参数为使用的KEY
			cipher.init(Cipher.DECRYPT_MODE, key);
			//先用base64解密
			byte[] encrypted = Base64.decodeBase64(txt);

			byte[] original = cipher.doFinal(encrypted);
			String decode = new String(original, "utf-8");
			return decode;
		}
		catch (Exception e)
		{
			log.error("解密失败", e);
			throw new RuntimeException("解密失败", e);
		}
	}
}

